package goclient

import (
	"context"
	"github.com/xtaci/kcp-go/v5"
	"net"
)

func kcpDialContext(ctx context.Context, network, addr string) (net.Conn, error) {
	chConn := make(chan net.Conn)
	chErr := make(chan error)
	defer close(chConn)
	defer close(chErr)
	go func() {
		var sessNotSend *kcp.UDPSession
		defer func() {
			recover()
			if sessNotSend != nil {
				sessNotSend.Close()
			}
		}()
		conn, err := kcp.DialWithOptions(addr, nil, 10, 1)
		if err != nil {
			chErr <- err
			return
		}
		sessNotSend = conn
		chConn <- conn
		sessNotSend = nil
	}()
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case err := <-chErr:
		return nil, err
	case conn := <-chConn:
		return conn, nil
	}
}
